package org.tabcap.workspace.manager;

import java.io.File;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

import org.tabcap.TCInstance;
import org.tabcap.workspace.TCWorkspace;
import org.tabcap.workspace.document.TabCapDocument;
 
public class DefaultWorkspaceManager extends BaseWorkspaceManager
{
	protected int newCount;
	
	public DefaultWorkspaceManager(TCInstance instance)
	{
		super(instance);
	}
	
	public void openNew()
	{
		newCount++;
		addWorkspace(new TCWorkspace(new TabCapDocument(newCount)));
	}

	public void open()
	{
		JFileChooser chooser = new JFileChooser(currentDirectory);
		chooser.setMultiSelectionEnabled(true);
		if(chooser.showOpenDialog(instance.frame()) == JFileChooser.APPROVE_OPTION)
		{
			for(File file : chooser.getSelectedFiles())
				open(file.getAbsolutePath());
			currentDirectory = chooser.getCurrentDirectory().getAbsolutePath();
		}
	}

	public void open(String filepath)
	{
		if(workspaces.size() == 1 && activeWorkspace.document().isWorthless())
			closeWorkspace(activeWorkspace);
		if(!fileIsOpen(filepath))
			try
			{
				addWorkspace(new TCWorkspace(new TabCapDocument(filepath)));
			}
			catch (Exception e)
			{
				e.printStackTrace();
				JOptionPane.showMessageDialog(	instance.frame(),
												"Invalid file!",
												"Error!",
												JOptionPane.ERROR_MESSAGE);
			}
		else
			selectWorkspace(filepath);
	}

	public void save()
	{
		saveWorkspace(activeWorkspace);
	}

	public void saveAs()
	{
		saveWorkspaceAs(activeWorkspace);
	}

	public void saveAll()
	{
		TCWorkspace ws = activeWorkspace;
		for(TCWorkspace workspace : workspaces)
		{
			selectWorkspace(workspace);
			saveWorkspace(workspace);
		}
		selectWorkspace(ws);
	}

	public void closeCurrent()
	{
		closeWorkspace(activeWorkspace);
		if(tabs.getTabCount() <= 0)
			openNew();
	}

	public void closeAll()
	{
		while(!workspaces.isEmpty())
		{
			TCWorkspace workspace = workspaces.getFirst();
			selectWorkspace(workspace);
			closeWorkspace(workspace);
		}
		openNew();
	}

	public void undo() { if(activeWorkspace != null) activeWorkspace.document().undo(); }
	public void redo() { if(activeWorkspace != null) activeWorkspace.document().redo(); }
	public void cut() { if(activeWorkspace != null) activeWorkspace.document().cut(); }
	public void copy() { if(activeWorkspace != null) activeWorkspace.document().copy(); }
	public void paste() { if(activeWorkspace != null) activeWorkspace.document().paste(); }
}